<template>
  <div>
    <van-cell :title="item" icon="search"
    v-for="(item,index) in suggestionList"
    :key="index"
    >
    <div slot="title" @click="$emit('search', item)" v-html="lightHeight(item)">

    </div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search/suggestion'
import { debounce } from 'lodash'
export default {
  name: 'suggestion',
  data () {
    return {
      suggestionList: JSON.parse(localStorage.getItem('user_history'))
    }
  },
  props: {
    search_txt: {
      type: String,
      required: true
    }
  },
  created () {

  },
  watch: {
    // 侦听文本框值的变化，此时需要用到特殊属性，就要写一个对象，由handler函数代替执行
    search_txt: {
      // 输入框有值，就发起请求，获取联想建议
      handler: debounce(function (newval) {
        // console.log(this)
        this.getSuggestion(newval)
      }, 800),
      // 该属性可以在值发生变化马上调用handler函数
      immediate: true
    }
  },
  methods: {
    async getSuggestion (newval) {
      try {
        const { data: res } = await getSearchSuggestions(newval)
        // console.log(res)
        this.suggestionList = res.data.options
      } catch (err) {
        this.$toast.fail('获取建议失败！')
      }
    },
    // 对匹配到的数据，进行高亮显示
    lightHeight (item) {
      const reg = new RegExp(this.search_txt, 'gi')
      item = item.replace(reg, `<span style="color:red">${this.search_txt}</span>`)
      return item
    }
  }
}
</script>

<style scoped lang='less'>

</style>
